package cn.ycc1.boot3video.video;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

public class HlsMasterPlaylistBuilder {
    private final Properties config;

    public HlsMasterPlaylistBuilder(Properties config) {
        this.config = config;
    }

    public String buildDynamicMasterPlaylist(String baseUrl, String videoId) {
        StringBuilder master = new StringBuilder();
        master.append("#EXTM3U\n");
        master.append("#EXT-X-VERSION:3\n\n");

        // 从配置读取清晰度设置
        String[] qualities = config.getProperty("hls.qualities", "1080p,720p,480p,360p").split(",");

        for (String quality : qualities) {
            int bandwidth = Integer.parseInt(config.getProperty("hls." + quality + ".bandwidth", "1000000"));
            String resolution = config.getProperty("hls." + quality + ".resolution", "1280x720");
            String codecs = config.getProperty("hls." + quality + ".codecs", "avc1.64001f,mp4a.40.2");

            master.append("#EXT-X-STREAM-INF:")
                    .append("BANDWIDTH=").append(bandwidth)
                    .append(",RESOLUTION=").append(resolution)
                    .append(",CODECS=\"").append(codecs).append("\"")
                    .append(",NAME=\"").append(quality).append("\"")
                    .append("\n")
                    .append(baseUrl).append("/").append(videoId).append("/").append(quality).append(".m3u8")
                    .append("\n\n");
        }

        return master.toString();
    }

    // 使用方法
    public static void main(String[] args) throws Exception {
        Properties config = new Properties();
        config.load(Files.newInputStream(Paths.get("hls-config.properties")));

        HlsMasterPlaylistBuilder builder = new HlsMasterPlaylistBuilder(config);
        String masterPlaylist = builder.buildDynamicMasterPlaylist(
                "https://cdn.example.com/videos",
                "movie_123"
        );

        System.out.println(masterPlaylist);
    }
}
